/**
 * TetisDB
 *
 * Thread para auto-salvamento do SnapShot
 */

package br.com.tetisdb.io.snapShot;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

import br.com.tetisdb.domain.TetisDomain;
import br.com.tetisdb.lang.TetisHashMap;

public class ThreadSnapShot extends Thread {
    //dominio dessa thread
    private TetisDomain domain;
    //se eh pra continuar
    private boolean continua = true;
    
    /**
     * Construtor padrao
     *
     * @param domain TetisDomain dessa Thread
     */
    public ThreadSnapShot(TetisDomain domain) {
        this.domain = domain;
    }
    
    /**
     * Metodo de execucao da Thread
     */
    public void run() {
        try {
            while (continua) {
                try {
                    sleep(domain.getConfigure().getTimeSnapShot());                    
                    takeSnapShot(domain.getSnapShotManager().getSnapShot());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            
        } catch (Exception e) {
        }
    }
    
    /**
     * Metodo para parar a thread
     */
    public void parar() {
        continua = false;
    }
    
    @Override
    public String toString() {
        return "ThreadSnapShot";
    }
    
    /**
     * Metodo que recebe o hash a ser gravado e cria o snapshot.
     */
    public synchronized void takeSnapShot(TetisHashMap<String, Object> mapa) throws FileNotFoundException, IOException {
        String path = domain.getCompleteDataPath() + File.separator
                + domain.getSnapShotManager().getNextSnapShotID()
                + SnapShotManager.EXTENSAO_TETIS;
        
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path));
        
        oos.writeObject(mapa);
        oos.close();
    }
}
